import React, { Component } from 'react';
import { Table, Tabs, Input, Button, Alert, Icon, Layout, message, Row, Col, DatePicker, TimePicker, Divider } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
 
import './style/nurseConfig.less';//引入样式

const TabPane = Tabs.TabPane;
const {
    Header, Footer, Sider, Content,
} = Layout;
let userData;
class NurseExcuteConfigTabs extends Component {

    constructor(props) {
        super(props);
        this.state = {
            multipleFlag: false,
            startIndex: '',
            title: [
                {
                    title: '描述',
                    dataIndex: 'descripts',
                    width: '150px',
                    key: 'descripts',
                }
            ],
            sheetColumns: [{
                title: '代码',
                dataIndex: 'code',
                key: 'code',
                width: '35%',
                render: (text, record, index) => {
                    if (record.editable) {
                        return (
                            <Input
                                style={{ width: '100px' }}
                                value={text}
                                autoFocus
                                onChange={e => this.handleFieldChange(e, 'code', record, index)}
                                placeholder="代码"
                            />
                        )
                    }
                    return text;
                }
            }, {
                title: '名称',
                dataIndex: 'descripts',
                key: 'descripts',
                width: '45%',
                render: (text, record, index) => {
                    if (record.editable) {
                        return (
                            <Input
                                style={{ width: '135px' }}
                                value={text}
                                placeholder="名称"
                                onChange={e => this.handleFieldChange(e, 'descripts', record, index)}
                            />
                        )
                    }
                    return text;
                }
            }, {
                title: '操作',
                key: 'action',
                render: (text, record, index) => {
                    return (
                        <span>
                            <a onClick={e => this.handleSaveRow(e, record)}>保存</a>
                            <Divider type="vertical" />
                            <br />
                            <a onClick={e => this.handleEditRow(e, record, index)}>编辑</a>
                        </span>
                    );
                }

            }
            ],
            column: [],
            sheet: [],
            button: [],
            ordStatus: [],
            priority: [],
            ordCat: [],
            usage: [],
            spec: [],
            recLoc: [],
            stage: [],
            dispose: [],
            columnKeys: [],
            buttonKeys: [],
            priorityKeys: [],
            ordCatKeys: [],
            specKeys: [],
            recLocKeys: [],
            stageKeys: [],
            disposeKeys: [],
            ordStatusKeys: [],
            usageKeys: [],
            selectIndex: '',
            showHeader: false,
            leftloading: true,
            rightloading: true,
            sheetCode: '',
            setClassName: 'clickRowStylee',
            hospID: '1',
            startDate: '2010-03-15',
            startTime: '00:00',
            endDate: '2010-03-15',
            endTime: '23:59:59',
            tabsActiveKey: '1',

        }
        userData= sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
    }
    newMember = () => {

        const newData = this.state.sheet
        newData.push({
            code: '',
            descripts: '',
            editable: true,
        });
        this.handleCleanSelect();
        this.setState({ data: newData });
    };
    getData = (record) => {
        let leftloading = true;
        let rightloading = true;
        let sheetCode = "";
        if (record != "") {
            sheetCode = record.code
        }
        if (!(this.state.selectSheet === '')) {
            leftloading = false;
        }
        this.setState(
            {
                leftloading: leftloading,
                rightloading: rightloading
            });
        let data = {
            "params": [{
                sheetCode: sheetCode,
                hospID: userData.hospID,
            }]
        };

        $http.post('urlDeault', this, {
            code: "04010004",
            data: data,
            success: function (res) {
                let sheet = [], button = [], column = [], priority = [], ordCat = [], spec = [], recLoc = [], stage = [], ordStatus = [], usage = [], dispose = []
                let buttonKeys = [], columnKeys = [], priorityKeys = [], ordCatKeys = [], specKeys = [], recLocKeys = [], stageKeys = [], ordStatusKeys = [], usageKeys = [], disposeKeys = []
                let startDate = res.startDate, startTime = res.startTime, endDate = res.endDate, endTime = res.endTime
                sheet = res.result.sheet;
                button = res.result.button;
                column = res.result.column;
                priority = res.result.priority;
                ordCat = res.result.ordCat;
                spec = res.result.spec;;
                recLoc = res.result.recLoc;
                stage = res.result.stage;
                ordStatus = res.result.ordStatus;
                usage = res.result.usage;
                dispose = res.result.dispose;
                disposeKeys = res.result.disposeKeys;
                buttonKeys = res.result.buttonKeys;
                columnKeys = res.result.columnKeys;
                priorityKeys = res.result.priorityKeys;
                ordCatKeys = res.result.ordCatKeys;
                specKeys = res.result.specKeys;
                recLocKeys = res.result.recLocKeys;
                stageKeys = res.result.stageKeys;
                ordStatusKeys = res.result.ordStatusKeys;
                usageKeys = res.result.usageKeys;
                this.setState(
                    {
                        selectSheet: record,
                        sheet: sheet,
                        button: button,
                        column: column,
                        priority: priority,
                        ordCat: ordCat,
                        spec: spec,
                        recLoc: recLoc,
                        stage: stage,
                        ordStatus: ordStatus,
                        usage: usage,
                        dispose: dispose,
                        buttonKeys: buttonKeys,
                        columnKeys: columnKeys,
                        priorityKeys: priorityKeys,
                        ordCatKeys: ordCatKeys,
                        specKeys: specKeys,
                        recLocKeys: recLocKeys,
                        stageKeys: stageKeys,
                        ordStatusKeys: ordStatusKeys,
                        usageKeys: usageKeys,
                        disposeKeys: disposeKeys,
                        startDate: startDate,
                        startTime: startTime,
                        endDate: endDate,
                        endTime: endTime,
                        tabsActiveKey: "1",
                        leftloading: false,
                        rightloading: false,
                    }
                );
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }
    getdataRowId = (data, key) => {

        let idStr = "";
        for (var i = 0; i < key.length; i++) {
            if (idStr === "") {
                idStr = data[key[i]].id;
            }
            else {
                idStr = idStr + "^" + data[key[i]].id;
            }
        }
        return idStr;
    }
    unique5(arr) {
        var x = new Set(arr);
        return [...x];
    }
    saveData = (record) => {
        let rightloading = true, leftloading = false;
        if (record.editable) {
            record.editable = false;
            leftloading = true;
        }

        this.setState(
            {
                leftloading: leftloading,
                rightloading: rightloading
            });
        let data = {
            "params": [{
                sheetCode: record.code,
                hospID: userData.hospID,
                sheetDesc: record.descripts,
                startDate: this.state.startDate,
                startTime: this.state.startTime,
                endDate: this.state.endDate,
                endTime: this.state.endTime,
                userID: userData.userID,
                button: this.getdataRowId(this.state.button, this.state.buttonKeys),
                column: this.getdataRowId(this.state.column, this.state.columnKeys),
                priority: this.getdataRowId(this.state.priority, this.state.priorityKeys),
                ordCat: this.getdataRowId(this.state.ordCat, this.state.ordCatKeys),
                spec: this.getdataRowId(this.state.spec, this.state.specKeys),
                recLoc: this.getdataRowId(this.state.recLoc, this.state.recLocKeys),
                stage: this.getdataRowId(this.state.stage, this.state.stageKeys),
                ordStatus: this.getdataRowId(this.state.ordStatus, this.state.ordStatusKeys),
                usage: this.getdataRowId(this.state.usage, this.state.usageKeys),
                dispose: this.getdataRowId(this.state.dispose, this.state.disposeKeys),
            }]
        };

        $http.post('urlDeault', this, {
            code: "04010005",
            data: data,
            success: function (res) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                }
            },
            error: function (error) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                message.error('失败：' + error);
            }
        });
    }
    componentDidMount() {
        //绑定键盘事件
        document.addEventListener("keyup", this.handleEnterKey);
        this.getData("");
    }
    componentWillUmount() {
        //取消键盘事件
        document.removeEventListener("keyup", this.handleEenterKey);
    }

    handleSaveRow = (e, record) => {
        if ((record.code === "") || (record.descripts === "")) {
            message.error('单据代码和描述不能为空');
            return;
        }
        this.setState({ sheetCode: record.code }, () => {
            this.saveData(record);
        })
    }
    handleEditRow = (e, record, index) => {
        let data = this.state.sheet;
        data[index].editable = true
        this.setState({ sheet: data })
    }

    handleEnterKey = (e) => {
        //shift 按键按下时触发

        let tabsActiveKey = parseInt(this.state.tabsActiveKey);
        if (tabsActiveKey == 10) { tabsActiveKey = 0 };
        tabsActiveKey = (tabsActiveKey + 1) + "";
        if (e.keyCode === 16) {
            this.setState({ multipleFlag: !this.state.multipleFlag });
        } else if (e.keyCode === 13) {
            this.setState({ tabsActiveKey: tabsActiveKey });
        }
    }
    handleFieldChange(e, field, record, index) {
        record[field] = e.target.value;
        var sheet = this.state.sheet
        sheet[index] = record
        this.setState({ sheet: sheet })
    }
    handleDateChange = (flag, date, dateString) => {
        this.setState({ [flag]: dateString });

    }
    handleTimeChange = (flag, time, timeString) => {
        this.setState({ [flag]: timeString });
    }
    handleCleanSelect = () => {
        this.setState(
            {
                buttonKeys: [],
                columnKeys: [],
                priorityKeys: [],
                ordCatKeys: [],
                specKeys: [],
                recLocKeys: [],
                stageKeys: [],
                ordStatusKeys: [],
                usageKeys: [],
                disposeKeys: [],
            })
    }
    onTabsChange = (tabsActiveKey) => {
        this.setState({ tabsActiveKey: tabsActiveKey });
    }
    tableRow = (tableName, record, index) => {
        return {
            /* 点击行 */
            onClick: (event) => {
                if (tableName === "sheet") {
                    return;
                }
                let selectedRowKeys = this.state.columnKeys;
                if (tableName === "sheetKeys") selectedRowKeys = this.state.sheetKeys;
                if (tableName === "buttonKeys") selectedRowKeys = this.state.buttonKeys;
                if (tableName === "columnKeys") selectedRowKeys = this.state.columnKeys;
                if (tableName === "priorityKeys") selectedRowKeys = this.state.priorityKeys;
                if (tableName === "ordCatKeys") selectedRowKeys = this.state.ordCatKeys;
                if (tableName === "specKeys") selectedRowKeys = this.state.specKeys;
                if (tableName === "recLocKeys") selectedRowKeys = this.state.recLocKeys;
                if (tableName === "stageKeys") selectedRowKeys = this.state.stageKeys;
                if (tableName === "ordStatusKeys") selectedRowKeys = this.state.ordStatusKeys;
                if (tableName === "usageKeys") selectedRowKeys = this.state.usageKeys;
                if (tableName === "disposeKeys") selectedRowKeys = this.state.disposeKeys;
                if (this.state.multipleFlag) {
                    ///按下shfit键后第一次点击为起始选中
                    let startIndex = this.state.startIndex
                    let endIndex = index;
                    if (startIndex === '') {
                        selectedRowKeys.push(index);
                        selectedRowKeys = this.unique5(selectedRowKeys);
                        this.setState({ startIndex: index, [tableName]: selectedRowKeys });
                    }
                    else {

                        if (startIndex > endIndex) {
                            let tmpIndex = startIndex;
                            startIndex = endIndex;
                            endIndex = tmpIndex;
                        }
                        for (var i = startIndex; i <= endIndex; i++) {
                            selectedRowKeys.push(i);
                        }
                        selectedRowKeys = this.unique5(selectedRowKeys);
                        this.setState({ startIndex: '', [tableName]: selectedRowKeys });
                    }
                }
                else {
                    let findFlag = false;
                    let start = 0;
                    selectedRowKeys.find(function (value, key) {
                        if (value === index) {
                            //遍历找到选中的数据，并记录下选中数据在数组中的key
                            findFlag = true;
                            start = key;
                        }
                    })
                    if (findFlag) {
                        //再次点击移除选中
                        selectedRowKeys.splice(start, 1);
                    }
                    else {
                        //将点击的行添加到选中
                        selectedRowKeys.push(index);
                    }
                }
                this.setState({ [tableName]: selectedRowKeys });
            },
            /* 双击行 */
            onDoubleClick: (event) => {
                if (tableName === "sheet") {
                    if (record.editable === true) {
                        return;
                    }
                    if (record.code === "") {
                        return;
                    }
                    else {
                        this.getData(record);
                    }
                    return;
                }
                return;
            },
            /* 鼠标移入 */
            onMouseEnter: (event) => {

            },
            /* 鼠标移出 */
            onMouseLeave: (event) => {

            }
        };
    }




    render() {
        const buttonSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ buttonKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.buttonKeys
        };
        const columnSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ columnKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.columnKeys
        };
        const prioritySelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ priorityKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.priorityKeys
        };
        const ordCatSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ ordCatKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.ordCatKeys
        };
        const specSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ specKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.specKeys
        };
        const recLocSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ recLocKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.recLocKeys
        };
        const stageSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ stageKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.stageKeys
        };
        const ordStatusSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ ordStatusKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.ordStatusKeys
        };
        const usageSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ usageKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.usageKeys
        };
        const disposeSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ disposeKeys: selectedRowKeys })
            },
            selectedRowKeys: this.state.disposeKeys
        };
        let marginTop = 16;
        if (this.state.sheet.length === 0) marginTop = 200;


        return (
            <Layout className="nurseConfig">
                <Sider
                    width="30%"
                    className="ant-layout-sider"
                    theme="light"
                    breakpoint="lg"
                    collapsedWidth="0"
                    onBreakpoint={(broken) => { }}
                    onCollapse={(collapsed, type) => { }}
                >
                    <Row style={{ backgroundColor: '#E6F7FF', height: '40px' }}>
                        <Col span={15}>
                            <span style={{ fontsize: '14px' }}>添加单据</span>
                        </Col>
                        <Col>
                            <Button
                                type="primary"
                                icon="save"
                            >保存配置</Button>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <Table
                                columns={this.state.sheetColumns}
                                dataSource={this.state.sheet}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "sheet")}
                                rowClassName={(record, index) => {
                                    if (record.code === this.state.sheetCode) {
                                        return "clickRowStyle";
                                    }
                                    return;

                                }}
                                loading={this.state.leftloading}
                            />
                        </Col>
                    </Row>

                    <Button
                        style={{ width: '100%', marginTop: marginTop, marginBottom: 8 }}
                        type="dashed"
                        onClick={this.newMember}
                        icon="plus"
                    >
                        新增单据
                    </Button>

                </Sider>
                <Layout>
                    <Tabs
                        defaultActiveKey="1"
                        activeKey={this.state.tabsActiveKey}
                        onChange={this.onTabsChange}
                        tabPosition="top"
                        style={{ height: "100%" }}
                    >
                        <TabPane tab="按钮时间" key="1">
                            <Col className="tablBorder">
                                <Table
                                    showHeader={this.state.showHeader}
                                    bordered="true"
                                    rowSelection={buttonSelection}
                                    columns={this.state.title}
                                    dataSource={this.state.button}
                                    pagination={false}
                                    onRow={this.tableRow.bind(this, "buttonKeys")}
                                    scroll={{ y: 350 }}
                                    loading={this.state.rightloading}
                                />
                                <Row>
                                    <Col span={1} style={{ width: "45%" }}>
                                        <DatePicker
                                            key="startDate"
                                            defaultValue={moment(this.state.startDate, 'YYYY-MM-DD')}
                                            value={moment(this.state.startDate, 'YYYY-MM-DD')}
                                            style={{ paddingTop: 10, paddingRight: 10 }}
                                            placeholder="开始日期"
                                            onChange={this.handleDateChange.bind(this, "startDate")} />
                                    </Col>
                                    <Col span={1} style={{ width: "45%" }}>
                                        <TimePicker
                                            key="startTime"
                                            style={{ paddingTop: 10 }}
                                            defaultValue={moment(this.state.startTime, 'HH:mm:ss')}
                                            onChange={this.handleTimeChange.bind(this, "startTime")} />
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={1} style={{ width: "45%" }}>
                                        <DatePicker
                                            key="endDate"
                                            defaultValue={moment(this.state.startDate, 'YYYY-MM-DD')}
                                            value={moment(this.state.startDate, 'YYYY-MM-DD')}
                                            style={{ paddingTop: 10, paddingRight: 10 }}
                                            placeholder="结束日期"
                                            onChange={this.handleDateChange.bind(this, "endDate")} />
                                    </Col>
                                    <Col span={1} style={{ width: "45%" }}>
                                        <TimePicker
                                            key="endTime"
                                            style={{ paddingTop: 10 }}
                                            defaultValue={moment(this.state.endTime, 'HH:mm:ss')}
                                            onChange={this.handleTimeChange.bind(this, "endTime")} />
                                    </Col>
                                </Row>
                            </Col>
                        </TabPane>
                        <TabPane tab="显示列" key="2">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={columnSelection}
                                columns={this.state.title}
                                dataSource={this.state.column}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "columnKeys")}
                                loading={this.state.rightloading}
                                scroll={{ y: 350 }}
                            />
                        </TabPane>
                        <TabPane tab="医嘱子类" key="3">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={ordCatSelection}

                                columns={this.state.title}
                                dataSource={this.state.ordCat}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "ordCatKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>

                        <TabPane tab="医嘱状态" key="4">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={ordStatusSelection}
                                columns={this.state.title}
                                dataSource={this.state.ordStatus}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "ordStatusKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />

                        </TabPane>
                        <TabPane tab="医嘱阶段" key="5">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={stageSelection}
                                columns={this.state.title}
                                dataSource={this.state.stage}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "stageKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>
                        <TabPane tab="处置状态" key="6">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={disposeSelection}
                                columns={this.state.title}
                                dataSource={this.state.dispose}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "disposeKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>
                        <TabPane tab="医嘱用法" key="7">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={usageSelection}
                                columns={this.state.title}
                                dataSource={this.state.usage}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "usageKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />

                        </TabPane>
                        <TabPane tab="医嘱优先级" key="8">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={prioritySelection}
                                columns={this.state.title}
                                dataSource={this.state.priority}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "priorityKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>
                        <TabPane tab="标本名称" key="9">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={specSelection}
                                columns={this.state.title}
                                dataSource={this.state.spec}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "specKeys")}
                                scroll={{ y: 350 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>
                        <TabPane tab="接收科室" key="10">
                            <Table
                                showHeader={this.state.showHeader}
                                bordered="true"
                                rowSelection={recLocSelection}
                                columns={this.state.title}
                                dataSource={this.state.recLoc}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "recLocKeys")}
                                scroll={{ y: 400 }}
                                loading={this.state.rightloading}
                            />
                        </TabPane>

                    </Tabs>
                </Layout>
            </Layout>

        )
    }
}
export default NurseExcuteConfigTabs;  